// @flow
import React from 'react'
import styles from './CustomerFillter.css'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { Input, Row, Col, Button } from 'antd'
import { connect } from 'react-redux'

type Props = {
  userId: string,
  getData: Function
}

type State = {
  eventName: string,
  keyName: string,
  eventType: Array<Object>,
  customer: Array<Object>,
  devices: Array<Object>
}

class Fillter extends React.Component {
  props: Props
  state: State
  searchInfo: Object
  handleKeyName: Function
  handleSearch: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      eventType: [{ value: '', label: '全部' }],
      eventName: '',
      keyName: '',
      customer: [{ id: '', name: '全部' }],
      devices: [{ id: '', name: '全部' }]
    }
    this.handleKeyName = this.handleKeyName.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.searchInfo = {}
  }

  componentDidMount () {
    // this.getFillterData()
    this.getFillterDatas(`${__SERVICE_API__}sys/dicts?type=eventType`, 'eventType')
    this.getFillterDatas(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=200000`, 'customer')
    this.getFillterDatas(`${__SERVICE_API__}device/devices?pageSize=200000`, 'devices')
  }
  getFillterDatas (url: string, name: string) {
    universalFetch(url)
    .then(res => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      let data = this.state[name]
      data.push(...json.result)
      this.setState({ [name]: data })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }
  handleSearch () {
    let { keyName } = this.searchInfo
    //  不确定是否有值,没有则设置为空
    keyName = keyName || ''
    let searchQuery = `&message=${keyName}`
    this.props.getData(searchQuery)
  }
  handleKeyName (e: any) {
    this.searchInfo.keyName = e.target.value
  }
  render () {
    return (
      <div className={styles['searchBox']}>
        <Row gutter={24} justify='center'>
          <Col className={styles['ant-col-2']} span={3}>
            <div className='gutter-box'>
              <Input placeholder='关键字'
                style={{ width: 300 }} onInput={this.handleKeyName} onPressEnter={this.handleSearch} />
            </div>
          </Col>
          <Button icon='search' onClick={this.handleSearch} style={{ marginLeft: 200 }} />
        </Row>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Fillter)
